<?php
/**
 * Created by b17
 * 3/5/12 5:04 PM
 */

class AuthController extends G4T_Controller
{
    protected $_user;

    protected $_session;

    public function init()
    {
        parent::init();
        $this->_user = Zend_Auth::getInstance()->getStorage()->read();
        $this->_session = new \Zend_Session_Namespace('auth');
    }

    private function _displayOAuthUrls()
    {
        $googleAuthUrl = \TBS\Auth\Adapter\Google::getAuthorizationUrl();
        $this->view->googleAuthUrl = $googleAuthUrl;
        $twitterAuthUrl = \TBS\Auth\Adapter\Twitter::getAuthorizationUrl();
        $this->view->twitterAuthUrl = $twitterAuthUrl;
        $facebookAuthUrl = \TBS\Auth\Adapter\Facebook::getAuthorizationUrl();
        $this->view->facebookAuthUrl = $facebookAuthUrl;
    }

    /**
     * Google oAuth.
     */
    public function oauth2callbackAction()
    {
        $adapter = new \TBS\Auth\Adapter\Google($this->_getParam('code'));
        $result = $adapter->authenticate();
        if ($result->isValid()) {
            $usersManager = new \Managers\Users();
            try {
                $user = $usersManager->authByOpenId($result->getIdentity());
                $this->rememberMe($user);
                $this->_redirect('/user');
            } catch (LogicException $e) {
                $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::LATER);
                $this->_redirect('/login');
            }
        }
        $this->_flashMessenger->addMessage(join("<br/>", $result->getMessages()), Lib_Flash::ERROR, Lib_Flash::LATER);
        $this->_redirect('/');
    }

    public function logoutAction()
    {
        \Zend_Auth::getInstance()->clearIdentity();
        setcookie('user', '', time(), '/');
        $this->_redirect('/');
    }

    public function registerAction()
    {
        if ($this->_user) {
            $this->_redirect('/');
        }

        $form = new App_Form_User_Register();

        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            if ($form->isValid($params)) {
                $values = $form->getValues();
                $usersManager = new \Managers\Users();
                $usersManager->create($params);
                $usersManager->auth($values['email'], $values['password']);
                $this->_redirectWhenLoginSuccess();
            }
        }

        $this->view->form = $form;
    }

    public function loginAction()
    {
        if ($this->_user) {
            $this->_redirect('/');
        }

//        $this->_displayOAuthUrls();

        $form = $this->getLoginForm();

        if ($this->_request->isPost()) {
            if ($form->isValid($this->_getAllParams())) {
                $values = $form->getValues();
                $usersManager = new \Managers\Users();
                try {
                    $result = $usersManager->auth($values['email'], $values['password']);
                    if ($result) {
                        if ($values['remember']) {
                            $this->rememberMe($result);
                        }
                        $this->_session->tries = 0;
                        $this->_redirectWhenLoginSuccess();
                    } else {
                        $this->_session->tries = intval($this->_session->tries) + 1;
                        $this->_flashMessenger->addMessage('Invalid email\password.', Lib_Flash::ERROR, Lib_Flash::NOW);
                    }
                } catch (LogicException $e) {
                    $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::NOW);
                }
            }
        }

        $this->view->form = $form;
    }

    private function getLoginForm()
    {
        $formBuilder = \G4T\Form\FormBuilder::createFormBuilder(\Managers\Users::TABLE)
            ->addField('email', 'email', array('label' => 'Email'))
            ->addField('password', 'password', array('label' => 'Password'))
            ->addField('remember', 'boolean', array('label' => 'Remember me'));
        if (intval($this->_session->tries) > 2) {
            $formBuilder->addField('captcha', 'captcha');
        }
        $formBuilder->addField('submit', 'submit', array('label' => 'Ввойти', 'class' => 'btn'));
        $form = $formBuilder->getForm();
        return $form;
    }

    private function rememberMe($user)
    {
        $userManager = new \Managers\Users();
        $cookieData = $userManager->getCookieData($user);
        setcookie('user', $cookieData, time() + 365 * 24 * 3600, '/');
    }

    private function _redirectWhenLoginSuccess()
    {
        $url = $this->getSavedUrl() ? : '/';
        $this->_flashMessenger->addMessage('Welcome.', Lib_Flash::NOTICE, Lib_Flash::LATER);
        $this->_redirect($url);
    }
}
